package net.ufrog.common.converters;

import net.ufrog.common.utils.Strings;

import java.util.Map;
import java.util.Properties;

/**
 * @author ultrafrog, ufrog.net@gmail.com
 * @version 0.1, 2017-07-05
 * @since 0.1
 */
public class PropertiesConverter extends Converter<Properties> {

    @Override
    @SuppressWarnings("unchecked")
    public Properties convert(Object obj, Object defaultValue) {
        if (obj == null) {
            return null;
        } else if (obj instanceof Properties) {
            return Properties.class.cast(obj);
        } else if (obj instanceof Map) {
            Properties properties = new Properties();
            convertMapToProperties(null, Map.class.cast(obj), properties);
            return properties;
        } else {
            return null;
        }
    }

    @Override
    public Class<Properties> getType() {
        return Properties.class;
    }

    /**
     * @param key 键值
     * @param obj 内容
     * @param properties 属性
     */
    @SuppressWarnings("unchecked")
    private void convertMapToProperties(String key, Object obj, Properties properties) {
        if (obj instanceof Map) {
            Map.class.cast(obj).forEach((k, v) -> convertMapToProperties(Strings.empty(key) ? String.valueOf(k) : key + "." + String.valueOf(k), v, properties));
        } else if (obj != null) {
            properties.put(key, obj);
        }
    }
}
